package com.demo;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;


import java.io.UnsupportedEncodingException;

/**
 * 协议处理类
 *
 */
public class ProtocolChannelHandler extends ChannelInboundHandlerAdapter {



	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		System.out.println("[ProtocolChannelHandler] [accept connect from {}]"+ getAddress(ctx));
	}
	
	/**
	 * 读数据
	 */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
    	String address = getAddress(ctx);
		System.out.println("[ProtocolChannelHandler] [read from {}]"+address);
    	ByteBuf buf = (ByteBuf)msg;
    	
    	//读数据
    	byte[] request = new byte[buf.readableBytes()];
    	buf.readBytes(request);

		System.out.println(("[ProtocolChannelHandler] [client:{}] [data length:{}] [read data:{}]"+
				new Object[]{address, request.length , request}));
    	
    	//解析数据,并回传客户端结果
    	//ProtocolHandler handler = SpringContextHolder.getBean(ProtocolHandler.class);
    	//handler.handle(session, request, ctx);
    }
    
	@Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
		System.out.println("[ProtocolChannelHandler] [read commplete from {}]"+getAddress(ctx));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		System.out.println("[ProtocolChannelHandler] [exception from {}]"+ getAddress(ctx));
		cause.printStackTrace();
        ctx.close();
    }
    
    /**
     * 获取client端地址
     * @date 2015-6-24
     */
    private String getAddress(ChannelHandlerContext ctx) {
    	return ctx.channel().remoteAddress().toString();
    }
}